//Created by MyEclipse Struts
// XSL source (default): platform:/plugin/com.genuitec.eclipse.cross.easystruts.eclipse_4.1.0/xslt/JavaClass.xsl

package cn.agiledata.bank.transaction.action;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import cn.agiledata.bank.common.dao.AccountTemplateInter;
import cn.agiledata.bank.common.dao.ActionTypeTemplate;
import cn.agiledata.bank.common.dao.TransactionTemplate;
import cn.agiledata.bank.common.service.ICommonService;
import cn.agiledata.bank.common.service.PermissionService;
import cn.agiledata.bank.common.util.Constant;
import cn.agiledata.bank.common.util.ConvertUtil;
import cn.agiledata.bank.common.util.ForeDict;
import cn.agiledata.bank.common.util.UniqueIdentityUtil;
import cn.agiledata.bank.common.util.WeatherUtil;
import cn.agiledata.bank.hibernateBean.Account;
import cn.agiledata.bank.hibernateBean.Bank;
import cn.agiledata.bank.hibernateBean.Groups;
import cn.agiledata.bank.hibernateBean.ScoresHis;
import cn.agiledata.bank.hibernateBean.SubAccount;
import cn.agiledata.bank.hibernateBean.Transaction;
import cn.agiledata.bank.linkbank.service.WebPayService;
import cn.agiledata.bank.myspace.service.IMySpaceService;
import cn.agiledata.bank.scores.service.IScoresService;
import cn.agiledata.bank.scores.service.ScoresFactory;
import cn.agiledata.bank.transaction.form.FillMoneyForm;
import cn.agiledata.bank.transaction.service.FeeForVNV;
import cn.agiledata.bank.transaction.service.GetTransaction;
import cn.agiledata.bank.transaction.service.GetTransactionImpl;
import cn.agiledata.bank.transaction.service.TransactionFactory;

import com.vnv.infrastructure.action.IPBBaseAction;
import com.vnv.infrastructure.exception.IPBException;
import com.vnv.infrastructure.logic.IPBAppFactory;
import com.vnv.infrastructure.logic.IPBMgrFactory;



/** 
 * MyEclipse Struts
 * Creation date: 04-01-2006
 * 
 * XDoclet definition:
 * @struts.action validate="true"
 * @struts.action-forward name="fillMoney4" path="fillMoney4"
 */
public class FillMoneyBankAction extends IPBBaseAction {


	/** 
	 * Method execute
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 */	
	public ICommonService getCommonService() {
		ICommonService service = (ICommonService)IPBAppFactory.getObj(ICommonService.SERVICE_NAME);
		return service;
	}
	protected IMySpaceService getMySpaceService() throws IPBException {
		return (IMySpaceService) IPBAppFactory.getObj(IMySpaceService.MGR_ID);
	}
	public ActionForward preProcess(
		ActionMapping mapping,
		ActionForm form,
		HttpServletRequest request,
		HttpServletResponse response) throws Exception{
		
		long accountId = WeatherUtil.getAccountIdFromSession(request);
		TransactionActionHelper haHelper =TransactionActionHelper.getTransactionActionHelper();
		PermissionService pif = PermissionService.getPermissionService();
		if (!pif.hasPermission(request,Constant.PERMIS_TYPE_BANKDEPOSIT)){
			
			return mapping.findForward("permission");
		}
		
			ActionTypeTemplate att = (ActionTypeTemplate)
			IPBMgrFactory.getMgr("actionTypeTemplate");
			
			AccountTemplateInter at = (AccountTemplateInter)
			IPBMgrFactory.getMgr("accountTemplate");
			
			TransactionTemplate tt = (TransactionTemplate)
			IPBMgrFactory.getMgr("transactionTemplate");

		FillMoneyForm fill = (FillMoneyForm)form;
		fill.setErrorMsg("");

		//登录账户。同交易收款
		fill.setLoginAccount(at.getAccount(String.valueOf(accountId)));	
		Set set = fill.getLoginAccount().getSubAccounts();
		SubAccount defaultSA = initAccount(request).getDefaultSubAccount();
		if(!pif.isCorpOperator(request)){
			List nset = new ArrayList();
			nset.add(defaultSA);
			Iterator it = set.iterator();
			while(it.hasNext()){
				SubAccount sa = (SubAccount) it.next();
				if(sa.getId()==defaultSA.getId()){continue;}
				else{nset.add(sa);}
			}
			
			request.setAttribute("subAccounts", nset);
		}else{
			request.setAttribute("subAccounts", 
					pif.getSubAccounts(request, Constant.PERMIS_TYPE_BANKDEPOSIT, defaultSA));
		}

		
		
		if (fill.isIfFinished()){
			WeatherUtil.cleanForm(fill);
			//fill.setIfFinished(true);
			return mapping.findForward("firstStep");
		}
		String Action= request.getParameter("action");

		
		//从银行获得的数据
		//是否成功
		String successful = (String)request.getParameter("successful");
        String ifSuccess = Boolean.valueOf(successful).booleanValue() ? Constant.INSIDE_STATUS_YES 
        		: Constant.INSIDE_STATUS_NO;
		String tranId = (String)request.getParameter("orderId");
		String bankReturnCode = (String)request.getParameter("returnCode");
		
		if (successful != null){
			
			Transaction tran = tt.getTransactionByTranId(tranId);
			tt.saveTransactionByParameter(tranId,ifSuccess,bankReturnCode);
		
			fill.setTransactionId(tran.getTransId());
			fill.setAccount(tran.getAmount().toString());
			fill.setRatio(tran.getCreditFee().doubleValue());
			fill.setIfFinished(true);
			request.setAttribute("FillMoneyForm", fill);
			//
			String email=fill.getLoginAccount().getEmail();
			String mobile = fill.getLoginAccount().getMobile();
			//
			String subAccountBalance=at.getSubAccount(fill.getCreditEmail()).getAccountId();
			String balance=new DecimalFormat( "0.00" ).format(haHelper.getSubBalance(email==null?mobile:email, subAccountBalance));
			request.setAttribute("AccountBalance", balance);

			IScoresService iss = ScoresFactory.getScoresService();
			String url = ConvertUtil.getRequestURL(request);
			if(fill.getCredit().getAccount().getAccountType().equals(Constant.ACCOUNT_TYPE_BUYER)){
				ScoresHis sh = iss.getScoresHis(tran.getCredit().getAccount().getId(), Constant.SCORES_SOURCE_D, null);
				if (Constant.SCORES_ACTIVATE_STATUS_A.equals(tran.getCredit().getAccount().getActivateStatus())) {
					iss.setActivationStatus(tran.getCredit().getAccount().getId(),
							url);
				}
				request.setAttribute("ScoresHistory", sh);
			}
			
			//
			return mapping.findForward("thirdStep");
		}
		
		if (Action!= null && Action.equals("main")){
			WeatherUtil.cleanForm(fill);
			return mapping.findForward("firstStep");
		}
		
		fill.setActionType(Long.parseLong(Constant.ACTION_TYPE_A));
		fill.setAt(att.getActionTypeById(Long.parseLong(Constant.ACTION_TYPE_A)));
		
		
		ActionForward af = new ActionForward();
		
		//如果是银行卡充值
		if (fill.getActionType()==Long.parseLong(Constant.ACTION_TYPE_A)){
			//初始化交易对象
			Transaction tran = new Transaction();
			if (fill.getWhichPage()==1){
				af = mapping.findForward("firstStep");
			}
			if (fill.getWhichPage()==2){
				af = mapping.findForward("firstStep");
			}
			if (fill.getWhichPage()==3){
					//获得个人账户的银行卡充值id
				UniqueIdentityUtil uiu = new UniqueIdentityUtil();
				Groups group = getMySpaceService().getGroupByAccount(at.getSubAccount(fill.getCreditEmail())
						.getAccount(), Constant.GROUP_TYPE_A);
				FeeForVNV ff = (FeeForVNV) IPBMgrFactory.getMgr("FeeRatio");
				 fill.setRatio(ff.getDebitFee(at.getSubAccount(fill.getCreditEmail()), 
							Constant.ACTION_TYPE_A, new Double(fill.getAccount()), 
							group.getId().toString()));
//				fill.setRatio(ff.getCreditFee(tran));
				fill.setTransactionId(
						uiu.getTransactionSequence(Constant.ACCOUNT_TYPE_BUYER,Constant.MODEL_TYPE_BANKDEPOSIT));
				//获得银行卡充值的actiontype
				fill.setAt(att.getActionTypeById(fill.getActionType()));
				request.setAttribute("FillMoneyForm", fill);
				//
		 			
				//request.setAttribute("BankList",InitForString.dataDictMap.get("BANK_INFO"));
					
				request.setAttribute("BankList",getBankList());
				ICommonService service = getCommonService();
				if (service.compareAmounts(at.getSubAccount(fill.getCreditEmail()).getId().toString(),
						Constant.ACTION_TYPE_A, new Double(fill.getAccount()))!=0) {
					fill.setErrorMsg("充值操作失败,您的充值金额为"+new Double(fill.getAccount())+
							"元，本次交易手续费为"+fill.getRatio()+", 充值金额不足！");
					af = mapping.findForward("firstStep");
				}else{
					af = mapping.findForward("secondStep");
				}
			}
				if (fill.getWhichPage()==4){
					if (!at.ifAccountIsEffect(Double.parseDouble(fill.getAccount()))){
						fill.setErrorMsg("充值操作失败，请重新输入金额！");
						return mapping.findForward("firstStep");						
					}
					//交易收款方
					SubAccount subcre =
						at.getSubAccount(fill.getCreditEmail());
					fill.setCredit(subcre);

					SubAccount sub = at.getBankSubAccount();
					//付款方，内部银行账户
					tran.setDebit(sub);
					
					encapTransaction(tran,fill);
					
					//开户银行
					if (StringUtils.isNotEmpty(fill.getBankType()))
					{
						tran.setBankSeq(new Long(fill.getBankType()));
					}else{
						fill.setErrorMsg("充值操作失败，没有选择银行或者未开通银行！");
						request.setAttribute("BankList",getBankList());
						return mapping.findForward("secondStep");
					}
					
//					if (!at.ifHasBank(fill.getBankType())){
//						fill.setErrorMsg("充值操作失败，该银行没有开通，请另选银行！");
//						//request.setAttribute("BankList",InitForString.dataDictMap.get("BANK_INFO"));
//						request.setAttribute("BankList",at.getExistDefaultBank());
//						return mapping.findForward("secondStep");
//					}
					
					//步骤一，首先保存具体transaction，不做真实转账操作
					tran.setInsideStatus(Constant.INSIDE_STATUS_NO);
                                        //保存充值返回url
                                        tran.setSellerUrl(request.getParameter("merchantUrl"));
					//保存信息
					try {
						saveTransaction(tran);
					}catch (RuntimeException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						fill.setErrorMsg("充值操作失败，可能是因为操作超时，请重新登录！");
						return mapping.findForward("firstStep");
					}
					
					saveToken(request);
					request.setAttribute("banktype",tran.getBankSeq());
					request.setAttribute("orderid",tran.getTransId());
					request.setAttribute("payment",tran.getAmount());
					
					af = mapping.findForward("requestBank");
				}			
		}else{//如果是线下汇款
			if (fill.getWhichPage()==0){
				// TODO Auto-generated method stub
					af = mapping.findForward("main");
				}
			if (fill.getWhichPage()==2){
				fill.setAccount("");
				request.setAttribute("FillMoneyForm", fill);
				af = mapping.findForward("downsite1");
			}
			if (fill.getWhichPage()==3){
				fill.setDownsiteSerial(UniqueIdentityUtil.getRemitVerifyCode());
//				获得个人账户的银行卡充值id
				UniqueIdentityUtil uiu = new UniqueIdentityUtil();
				fill.setTransactionId(
						uiu.getTransactionSequence(Constant.ACCOUNT_TYPE_BUYER,Constant.MODEL_TYPE_REMIT));
				
				af = mapping.findForward("downsite2");
			}	
			if (fill.getWhichPage()==4){//保存方法
				//初始化交易对象
				Transaction tran = new Transaction();
				//交易状态
				tran.setTransStatus(Constant.TRANS_STATUS_INIT);	
				//保存动态生成的id
				tran.setVerifyCode(fill.getDownsiteSerial());
				encapTransaction(tran,fill);
				//保存信息
				saveTransaction(tran);
				
				af = mapping.findForward("downsite2");
			}
		}
		
		return af;
	}
	
	private Bank[] getBankList() {
		WebPayService webPayService = (WebPayService)IPBAppFactory.getObj(ForeDict.SERVICE_WEB_PAY);
		return webPayService.getSupportedNetBanks();
	}

	private void saveTransaction(Transaction tran) {
		
		GetTransaction getTran = new GetTransactionImpl();
		TransactionFactory tt = 
			getTran.getTransaction(Constant.ACTION_TYPE_A);
		
			try {
				tt.saveTransaction(tran);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
	}


	private void encapTransaction(Transaction tran,FillMoneyForm obj){
		//交易状态
		tran.setTransStatus(Constant.TRANS_STATUS_INIT);
		//收款方
		tran.setCredit(obj.getCredit());
		//交易编号
		if (obj.getTransactionId() == null){
			UniqueIdentityUtil uiu = new UniqueIdentityUtil();
			tran.setTransId(uiu.getTransactionSequence(Constant.ACCOUNT_TYPE_BUYER,Constant.MODEL_TYPE_BANKDEPOSIT));
		}else{
			tran.setTransId(obj.getTransactionId());
		}
                tran.setOrderId(tran.getTransId());
		//actionType
	 	tran.setActionType(obj.getAt());
		//交易金额
		tran.setAmount(new Double(obj.getAccount()));

		//封装插入日期和修改日期
		WeatherUtil.fillCreateAndUpdateInfo(tran,obj.getLoginAccount().getId().toString());
		//
		tran.setBeginDate(new Date());
		tran.setRemark(obj.getRemark());
	}
	private Account initAccount(HttpServletRequest request) throws IPBException {
		long accountId = WeatherUtil.getAccountIdFromSession(request);
		AccountTemplateInter at = (AccountTemplateInter) IPBMgrFactory
				.getMgr("accountTemplate");
		Account account = at.getAccount(String.valueOf(accountId));
		// request.setAttribute("subAccounts",acco.getSubAccounts());
		return account;
	}


}